package com.kcsj.service.user;

import com.kcsj.dao.User.UserDao;
import com.kcsj.domain.Count;
import com.kcsj.domain.user.User;
import com.kcsj.util.Condition;
import com.kcsj.util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */
public final class UserService {

	private UserDao userDao = UserDao.getInstance();
	private static UserService userService = new UserService();

	public UserService() {
	}

	public static UserService getInstance(){
		return UserService.userService;
	}

	public User find(Integer id) throws SQLException {
		Connection conn = JdbcHelper.getConn();
		User user = userDao.find(id, conn);
		JdbcHelper.close(conn);
		return user;
	}

	public Collection<User> findAll( List<Condition> conditionList) throws SQLException {
		Connection conn = JdbcHelper.getConn();
		Collection<User> users = userDao.findAll(conn,conditionList);
		users.removeIf(user -> user.getRole().getName().equals("超级管理员"));
		JdbcHelper.close(conn);
		return users;
	}

	public boolean update(User user) throws SQLException {
		Connection conn = JdbcHelper.getConn();
		boolean update = userDao.update(user, conn);
		JdbcHelper.close(conn);
		return update;
	}


	public boolean delete(Integer id) throws SQLException {
		Connection conn = JdbcHelper.getConn();
		boolean delete = userDao.delete(id, conn);
		JdbcHelper.close(conn);
		return delete;
	}

	//激活
	public void active(String code) throws SQLException {
		Connection conn = JdbcHelper.getConn();
		userDao.activeByCode(code,conn);
	}

	public void addUser(User user) throws SQLException {
		Connection conn = JdbcHelper.getConn();
		user.setActivationStatus(true);
		userDao.add(user, conn);
		JdbcHelper.close(conn);
	}

	public User login(String username) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		User user = userDao.login(connection, username);
		JdbcHelper.close(connection);
		return user;
	}

	public User findByCode(String code) throws SQLException{
		Connection conn = JdbcHelper.getConn();
		User userFindByCode = UserDao.getInstance().findByCode(code, conn);
		JdbcHelper.close(conn);
		return userFindByCode;
	}

	public ArrayList<Count> count(String sort) throws SQLException{
		Connection conn = JdbcHelper.getConn();
		if(sort.equals("role")){
			ArrayList<Count> counts = UserDao.getInstance().countByRoleId(conn);
			JdbcHelper.close(conn);
			return counts;
		}else {
			ArrayList<Count> counts = UserDao.getInstance().count(sort,conn);
			JdbcHelper.close(conn);
			return counts;
		}
	}
}
